<template>
  <div v-loading="loading">
    <div class="flex-between mb-10">
      <div></div>
      <!-- <el-input
        v-model="searchValue"
        placeholder="请输入"
        style="width: 240px"
        prefix-icon="Search"
        class="w-240"
        clearable
        @change="onSearch"
      >
      </el-input> -->
      <el-space size="default">
        <el-button type="primary" icon="Plus" @click="showAppend"
          >创建组</el-button
        >
      </el-space>
    </div>

    <common-table
      :table-type="tableType"
      :table-data="tableData"
      :on-selection-change="onSelectionChange"
      v-model:total="currentTotal"
      v-model:page="currentPage"
      v-model:pageSize="pageSize"
      :handle-current-change="handleCurrentChange"
      :row-key="getRowKey"
      :expand-row-keys="expandedRowsKeys"
      @expand-change="handleExpandChange"
      :showPagination="true"
    >
      <template #expand>
        <el-table-column type="expand">
          <template #default="props">
            <div class="team-detail" v-loading="detailLoading">
              <el-descriptions :column="1" style="margin-bottom: 10px">
                <el-descriptions-item label="小组名称:">{{
                  props.row.groupName
                }}</el-descriptions-item>
                <el-descriptions-item label="项目名称: ">{{
                  props.row.listName
                }}</el-descriptions-item>
                <el-descriptions-item label="第一阶段答辩得分:">
                  {{ props.row.dbFirst }}
                </el-descriptions-item>
                <el-descriptions-item label="第二阶段答辩得分:">{{
                  props.row.dbSecond
                }}</el-descriptions-item>
                <el-descriptions-item label="中期答辩得分:">{{
                  props.row.dbMid
                }}</el-descriptions-item>
                <el-descriptions-item label="终期答辩得分:">{{
                  props.row.dbTerminal
                }}</el-descriptions-item>
              </el-descriptions>
              <h3 style="margin-bottom: 20px">小组成员</h3>
              <common-table
                :table-type="membertableType"
                :table-data="props.row.group"
              >
                <template #operation>
                  <el-table-column label="操作" width="150" fixed="right">
                    <template #default="{ row }">
                      <el-button
                        link
                        type="primary"
                        @click="showMemberDetail(row)"
                      >
                        详情
                      </el-button>
                    </template>
                  </el-table-column>
                </template>
              </common-table>
              <h3 style="margin: 20px 0">附件</h3>
              <common-table
                :table-type="filetableType"
                :table-data="props.row.file"
              >
              </common-table>
            </div>
          </template>
        </el-table-column>
      </template>
      <template #operation>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click.stop="handleExpandChange(row)"
            >
              详情
            </el-button>
            <el-button link type="primary" @click.stop="showScoreDialog(row)">
              打分
            </el-button>
            <span @click.stop>
              <el-dropdown trigger="click">
                <el-button
                  type="primary"
                  link
                  style="line-height: 20px; margin-left: 12px"
                >
                  更多
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      style="justify-content: center"
                      @click="showEditor(row)"
                    >
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click="onDelete(row)"
                      style="justify-content: center"
                    >
                      删除
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click="onExport(row)"
                      style="justify-content: center"
                    >
                      导出小组成绩
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </span>
          </template>
        </el-table-column>
      </template>
    </common-table>

    <ScoreFormDialog ref="ScoreFormDialogRef" @refresh="refresh" />
    <TeamFormDialog ref="TeamFormDialogRef" @refresh="refresh" />
    <MemberDetailDrawer ref="MemberDetailDrawerRef" />
  </div>
</template>

<script setup lang="ts">
import TeamFormDialog from "./TeamFormDialog.vue";
import ScoreFormDialog from "./ScoreFormDialog.vue";
import MemberDetailDrawer from "@/views/member/MemberDetailDrawer.vue";

import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import api from "@/api";
import { tableType } from "./utils";
import { membertableType } from "@/views/member/utils";
import { filetableType } from "@/views/file/utils";
import { downloadByBlob } from "@/utils/index";

const loading = ref(false);
const detailLoading = ref(false);
const searchValue = ref("");

const ScoreFormDialogRef = ref();
const MemberDetailDrawerRef = ref();
const TeamFormDialogRef = ref();
const tableData = ref<any[]>([]);
const tableSelection = ref<any[]>([]);
const onSelectionChange = (val: any[]) => {
  tableSelection.value = val;
};

const expandedRowsKeys = ref<any[]>([]);
const currentRow = ref(null);

const getRowKey = (row: any) => row.id;
const handleExpandChange = (row: any) => {
  if (expandedRowsKeys.value.length > 0) {
    expandedRowsKeys.value = [];
    currentRow.value = null;
  } else {
    currentRow.value = row;
    getMemberData(row);
    getfileData(row);
    expandedRowsKeys.value = [row.id];
  }
};

function getfileData(row: any) {
  detailLoading.value = true;
  const index = tableData.value.findIndex((v) => v.id === row.id);
  api.file
    .listPageFile(1, 50, row.acc)
    .then((res: any) => {
      if (res.success) {
        tableData.value[index]["file"] = res.data.records;
        detailLoading.value = false;
      }
    })
    .catch(() => {
      tableData.value[index]["file"] = [];
      detailLoading.value = false;
    });
}

function getMemberData(row: any) {
  detailLoading.value = true;
  const index = tableData.value.findIndex((v) => v.id === row.id);
  api.groupDetail
    .selectGroupByID(row.acc)
    .then((res: any) => {
      if (res.success) {
        tableData.value[index]["group"] = res.data;
        detailLoading.value = false;
      }
    })
    .catch(() => {
      tableData.value[index]["group"] = [];
      detailLoading.value = false;
    });
}

function showScoreDialog(row: any) {
  ScoreFormDialogRef.value.open(row);
}
// Append
function showAppend() {
  TeamFormDialogRef.value.open();
}
// Editor
function showEditor(row: any) {
  TeamFormDialogRef.value.open(row);
}

// 组员详情
function showMemberDetail(row: any) {
  MemberDetailDrawerRef.value.open(row);
}

//Delete
function onDelete(row: any) {
  ElMessageBox.confirm(`确认删除 ${row.leader || ""} 小组吗?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      api.group.deleteTeam(row.id).then((res: any) => {
        ElMessage({
          message: res.message,
          type: res.success ? "success" : "error",
          grouping: true,
          showClose: true,
        });
        refresh();
      });
    })
    .catch(() => {});
}

/*
 * Static state
 * */
function getTableData(val: number) {
  loading.value = true;
  api.group
    .listPageTeam(val, 15)
    .then((res: any) => {
      if (res.success) {
        tableData.value = res.data.records;
        currentTotal.value = res.data.total;
        if (currentRow.value) {
          getMemberData(currentRow.value);
          getfileData(currentRow.value);
        }

        loading.value = false;
      }
    })
    .catch(() => {
      loading.value = false;
    });
}

//Pager
const currentPage = ref(1);
const currentTotal = ref(0);
const pageSize = ref(20);
const handleCurrentChange = (val: number) => {
  getTableData(val);
};

function refresh() {
  getTableData(currentPage.value);
}

onMounted(() => {
  getTableData(1);
});

function onExport(row: any) {
  loading.value = true;
  api.group
    .exportExcel(row.acc)
    .then((response) => {
      downloadByBlob(response, `${row.acc}小组成绩单.xlsx`);

      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
}
</script>
<style lang="scss" scope>
.team-detail {
  padding: 16px 20px;
}
</style>
